# coding=utf-8
"""
作者：董新强 
创建时间：2020-3-22
描述：能力管理
"""

from db_models.cat_abilities import CatAbilities
from db_models.orm_base import OrmBase
from framework.db_session import DbSession
from framework.msg import ok, failure
from framework.utilities import to_int, to_float
from services.admin.admin_base import AdminBase


class AbilityManage(AdminBase):
    def __init__(self, usr):
        super().__init__(usr)

    @AdminBase.admin(failure(msg='获取能力列表失败'))
    def get_list(self, pid=0):
        ls = []
        with DbSession.create() as db:
            query = db.query(CatAbilities).filter(CatAbilities.pid == pid).order_by(CatAbilities.name)
            for v in query:
                ls.append(OrmBase.get_dict(v))

        return ok(data=ls)

    @AdminBase.admin(failure(msg='获取能力列表失败'))
    def get_all_title_list(self):
        ls = []
        with DbSession.create() as db:
            query = db.query(CatAbilities.id, CatAbilities.name).order_by(CatAbilities.name)
            for id, name in query:
                ls.append({
                    'id': id,
                    'name': name
                })

        return ok(data=ls)

    @AdminBase.admin(failure(msg='获取详情失败'))
    def get_detail(self, id):
        with DbSession.create() as db:
            item = db.query(CatAbilities).filter(CatAbilities.id == id).first()
            return ok(data=OrmBase.get_dict(item))

    @AdminBase.admin(failure(msg='跟着状态失败'))
    def update_status(self, aid):
        with DbSession.create() as db:
            a = db.query(CatAbilities).filter(CatAbilities.id == aid).first()
            if not a:
                return failure(msg='能力不存在')
            if not a.status:
                a.status = 1
                return ok(data=1)
            a.status = 0
            return ok(data=0)

    @AdminBase.admin(failure(msg='保存失败'))
    def create_or_update(self, reqs):
        aid = to_int(reqs.get('id'))
        pid = to_int(reqs.get('pid'), 0)
        name = reqs.get('name', '').strip()
        w = to_float(reqs.get('w'))
        qnums = to_int(reqs.get('qnums'), 0)
        if not name:
            return failure(msg='请输入能力名称')
        with DbSession.create() as db:
            if aid:
                item = db.query(CatAbilities).filter(CatAbilities.id == aid).first()
                if not item:
                    return failure(msg='指定能力不存在')
            else:
                item = CatAbilities()
                item.pid = pid
                item.status = 0
                item.appid = 0

            item.name = name
            item.w = w
            item.qnums = qnums
            db.add(item)
        return ok(msg='保存成功')


if __name__ == '__main__':
    pass
